package com.heima.search.service.iml;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.search.entiy.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Resource
    private MongoTemplate mongoTemplate;
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        //1 参数检查
        if (userSearchDto==null|| StringUtils.isBlank(userSearchDto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页检查
        if (userSearchDto.getPageSize()>10){
            userSearchDto.setPageSize(10);
        }
        //3 执行查询 模糊查询
        Query query = Query.query(Criteria.where("associateWords")
                .regex(".*?" + userSearchDto.getSearchWords() + ".*"));
            query.limit(userSearchDto.getPageSize());
        List<ApAssociateWords> wordsList = mongoTemplate.find(query, ApAssociateWords.class);
        return  ResponseResult.okResult(wordsList);
    }
}
